package com.gdth.service;

import java.lang.ref.WeakReference;

import com.gdth.bank.utils.LogUtils;
import com.gdth.listener.impl.OnTelePhoneListenerImpl;
import com.gdth.listener.impl.PhoneStateListenerImpl;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

/**
 * @author Arvin
 * @version 2016-5-18 16:33:13 
 * 
 */
public class PhoneCallService extends Service{
	private static final String tag = "phonecallservice";
    TelephonyManager mTelephonyManager;
    
    PhoneStateListenerImpl mTelePhoneListener;
    
    /**
	 * 弱引用的录音
	 */
//	private WeakReference<PhoneMediaRecorder> mRecorder;
    private PhoneMediaRecorder mPhoneMediaRecorder;
	
	private PhoneMediaPlayer mMdieaPlayr;
	
	/**
     * 同一个应用内的不同组件间发送Broadcast
     */
    private LocalBroadcastManager mLocalBroadcastManager;
    
    private MyBroadcastReceiver mMyBroadcastReceiver;
        
    @Override    
    public void onCreate() {    
        super.onCreate();
        
        init();
    }    
        
    @Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
    	return null;
	}
    
    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        
        init();
    }
    
    /**
     * 启动
     */
    private void init(){ 
        
        //注册各种事件
        IntentFilter mIntentFilter = getIntentFilter();    

        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);

        mMyBroadcastReceiver = new MyBroadcastReceiver();
        mLocalBroadcastManager.registerReceiver(mMyBroadcastReceiver, mIntentFilter);
        
        mTelePhoneListener = new PhoneStateListenerImpl(new OnTelePhoneListenerImpl(mLocalBroadcastManager));
        
        mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        mTelephonyManager.listen(mTelePhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
        
        mMdieaPlayr = new PhoneMediaPlayer();
    }
    
    @Override    
    public void onDestroy() { 
    	releaseLastSocket();
    	
    	super.onDestroy();  
    }
    
    /**
	 * 注销
	 * @param mSocket
	 */
	private void releaseLastSocket() {
    	if (mMyBroadcastReceiver != null)
    		mLocalBroadcastManager.unregisterReceiver(mMyBroadcastReceiver);
    	
//    	if (mRecorder != null){
//    		PhoneMediaRecorder mPhoneMediaRecorder = mRecorder.get();
    		if (mPhoneMediaRecorder != null){
	    		mPhoneMediaRecorder.destory();
	    		mPhoneMediaRecorder = null;
    		}
//    	}
		
		if (null != mMdieaPlayr) {
			mMdieaPlayr.stopMusic();
			mMdieaPlayr = null;
		}
	}
    
    @Override    
    public int onStartCommand(Intent intent, int flags, int startId) {  
        return START_STICKY;    
    }
    
    private void startPhone(String number, String jcuuid, String jtuuid){
//    	PhoneMediaRecorder mPhoneMediaRecorder = new PhoneMediaRecorder();
    	mPhoneMediaRecorder = new PhoneMediaRecorder();
    	mPhoneMediaRecorder.setNumber(number);
    	mPhoneMediaRecorder.setJcuuid(jcuuid);
    	mPhoneMediaRecorder.setJtuuid(jtuuid);
    	
//    	mRecorder = new WeakReference<PhoneMediaRecorder>(mPhoneMediaRecorder);

    	//通知页面录音程序已准备
    	Intent intent = new Intent(PhoneCallState.READY);
		intent.putExtra("number", number);
		intent.putExtra("jcuuid", jcuuid);
		intent.putExtra("jtuuid", jtuuid);
    	mLocalBroadcastManager.sendBroadcast(intent);
    }
    
    private void startMusic(String uuid){
    	mMdieaPlayr.setMusic(uuid);
    }
    
    private void stopMusic(){
    	mMdieaPlayr.stopMusic();
    }


    /**
     * 广播接收器
     * @author mac1
     *
     */
	class MyBroadcastReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String phoneState = intent.getAction();    
	         
	        if (phoneState.equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
	        	if (mPhoneMediaRecorder != null) {
		            String phoneNum = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
	//	            PhoneMediaRecorder mPhoneMediaRecorder = mRecorder.get();
		            mPhoneMediaRecorder.setNumber(phoneNum);    
		            mPhoneMediaRecorder.setIsCommingNumber(false);
		            LogUtils.e(tag, "电话响起ACTION_NEW_OUTGOING_CALL" + phoneNum);
	        	}

	        }    
	            
	        if (phoneState.equals(PhoneCallState.DIALING)) {
	        }    
	            
	        if (phoneState.equals(PhoneCallState.ALERTING)) {
//	        	PhoneMediaRecorder mPhoneMediaRecorder = mRecorder.get();
	        	if (mPhoneMediaRecorder != null) {
	        		mPhoneMediaRecorder.setIsCommingNumber(true);
	        	}
	        }    
	            
	        if (phoneState.equals(PhoneCallState.ACTIVE)) {
//	        	PhoneMediaRecorder mPhoneMediaRecorder = mRecorder.get();
	        	LogUtils.e(tag, "电话响起ACTIVE");
	            if (mPhoneMediaRecorder != null && !mPhoneMediaRecorder.isStarted()) {   
	            	LogUtils.e(tag, "开始录音");
	            	mPhoneMediaRecorder.start();
	            }    
	        }    
	            
	        if (phoneState.equals(PhoneCallState.DISCONNECTED)) {  
//	        	PhoneMediaRecorder mPhoneMediaRecorder = mRecorder.get();
	    
	            if (mPhoneMediaRecorder != null && mPhoneMediaRecorder.isStarted()) {    //!recorder.isCommingNumber() && recorder.isStarted()
	            	Intent intents = new Intent(PhoneCallState.END);
	            	intents.putExtra("jtuuid", mPhoneMediaRecorder.getJtuuid());
	            	intents.putExtra("number", mPhoneMediaRecorder.getNumber());
	            	intents.putExtra("jcuuid", mPhoneMediaRecorder.getJcuuid());
	            	intents.putExtra("uuid", mPhoneMediaRecorder.getUuid());
	            	mLocalBroadcastManager.sendBroadcast(intents);
	            	LogUtils.e(tag, "电话录音结束,发出广播" + mPhoneMediaRecorder.getNumber());
	            	mPhoneMediaRecorder.destory();
	            	mPhoneMediaRecorder = null;
	            }    
	        }
	        
	        if (phoneState.equals(PhoneCallState.START)){
	        	String number = intent.getStringExtra("number");
	        	String jcuuid = intent.getStringExtra("jcuuid");
	        	String jtuuid = intent.getStringExtra("jtuuid");
	        	startPhone(number, jcuuid, jtuuid);
	        }
	        
	        if (phoneState.equals(PhoneCallState.MEDIA_STAER)){
	        	String uuid = intent.getStringExtra("uuid");
	        	startMusic(uuid);
	        }
	        
	        if (phoneState.equals(PhoneCallState.MEDIA_END)){
	        	stopMusic();
	        }
		}
	}
	
    /**
     * 发生本地广播
     * @param action
     */
    private void sendBroadcastByIntent(String action){
    	Intent intent = new Intent(action);
    	mLocalBroadcastManager.sendBroadcast(intent);
    }
    
    /**
	 * 注册各种广播
	 * @return
	 */
	private IntentFilter getIntentFilter(){
		IntentFilter mIntentFilter = new IntentFilter();    
		mIntentFilter.addAction(PhoneCallState.IDLE);    
        mIntentFilter.addAction(PhoneCallState.DIALING);    
        mIntentFilter.addAction(PhoneCallState.ALERTING);    
        mIntentFilter.addAction(PhoneCallState.ACTIVE);    
        mIntentFilter.addAction(PhoneCallState.DISCONNECTED);
        mIntentFilter.addAction(PhoneCallState.READY);
        mIntentFilter.addAction(PhoneCallState.START);
        mIntentFilter.addAction(PhoneCallState.END); 
        mIntentFilter.addAction(PhoneCallState.MEDIA_STAER);
        mIntentFilter.addAction(PhoneCallState.MEDIA_END);
        
        mIntentFilter.addAction("android.intent.action.PHONE_STATE");    
        mIntentFilter.addAction("android.intent.action.NEW_OUTGOING_CALL");
        
        return mIntentFilter;
	}

    
//  /**
//   * 电话监听事件
//   */
//  private OnTelePhoneListener mOnTelePhoneListener = new OnTelePhoneListener(){
//  	@Override
//  	public void CALL_STATE_IDLE() {
//  		// TODO Auto-generated method stub
//  		 
//  		Intent intent = new Intent(PhoneCallState.IDLE);
//  		intent.putExtra("msg", "电话空闲");
//  		sendBroadcast(intent);
//  	}
//
//  	@Override
//  	public void CALL_STATE_RINGING() {
//  		// TODO Auto-generated method stub
//  		sendBroadcastByIntent(PhoneCallState.ALERTING);
//  	}
//
//  	@Override
//  	public void CALL_STATE_OFFHOOK() {
//  		// TODO Auto-generated method stub
//  		sendBroadcastByIntent(PhoneCallState.ACTIVE);
//  	}
//  	
//  	@Override
//  	public void CALL_STATE_OFFHOOK_CALL() {
//  		// TODO Auto-generated method stub
//  		
//  		sendBroadcastByIntent(PhoneCallState.ACTIVE);
//  	}
//  	
//  	@Override
//  	public void CALL_STATE_OFFHOOK_DOWN(){
//  		sendBroadcastByIntent(PhoneCallState.DISCONNECTED);
//  	}
//  };
}
